home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / urllib.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  49.1 KB  |  1,437 lines

  1. """Open an arbitrary URL.
  2.  
  3. See the following document for more info on URLs:
  4. "Names and Addresses, URIs, URLs, URNs, URCs", at
  5. http://www.w3.org/pub/WWW/Addressing/Overview.html
  6.  
  7. See also the HTTP spec (from which the error codes are derived):
  8. "HTTP - Hypertext Transfer Protocol", at
  9. http://www.w3.org/pub/WWW/Protocols/
  10.  
  11. Related standards and specs:
  12. - RFC1808: the "relative URL" spec. (authoritative status)
  13. - RFC1738 - the "URL standard". (authoritative status)
  14. - RFC1630 - the "URI spec". (informational status)
  15.  
  16. The object returned by URLopener().open(file) will differ per
  17. protocol.  All you know is that is has methods read(), readline(),
  18. readlines(), fileno(), close() and info().  The read*(), fileno()
  19. and close() methods work like those of open files.
  20. The info() method returns a mimetools.Message object which can be
  21. used to query various info about the object, if available.
  22. (mimetools.Message objects are queried with the getheader() method.)
  23. """
  24.  
  25. import string
  26. import socket
  27. import os
  28. import time
  29. import sys
  30. from urlparse import urljoin as basejoin
  31.  
  32. __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
  33.            "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
  34.            "urlencode", "url2pathname", "pathname2url", "splittag",
  35.            "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
  36.            "splittype", "splithost", "splituser", "splitpasswd", "splitport",
  37.            "splitnport", "splitquery", "splitattr", "splitvalue",
  38.            "splitgophertype", "getproxies"]
  39.  
  40. __version__ = '1.16'    # XXX This version is not always updated :-(
  41.  
  42. MAXFTPCACHE = 10        # Trim the ftp cache beyond this size
  43.  
  44. # Helper for non-unix systems
  45. if os.name == 'mac':
  46.     from macurl2path import url2pathname, pathname2url
  47. elif os.name == 'nt':
  48.     from nturl2path import url2pathname, pathname2url
  49. elif os.name == 'riscos':
  50.     from rourl2path import url2pathname, pathname2url
  51. else:
  52.     def url2pathname(pathname):
  53.         """OS-specific conversion from a relative URL of the 'file' scheme
  54.         to a file system path; not recommended for general use."""
  55.         return unquote(pathname)
  56.  
  57.     def pathname2url(pathname):
  58.         """OS-specific conversion from a file system path to a relative URL
  59.         of the 'file' scheme; not recommended for general use."""
  60.         return quote(pathname)
  61.  
  62. # This really consists of two pieces:
  63. # (1) a class which handles opening of all sorts of URLs
  64. #     (plus assorted utilities etc.)
  65. # (2) a set of functions for parsing URLs
  66. # XXX Should these be separated out into different modules?
  67.  
  68.  
  69. # Shortcut for basic usage
  70. _urlopener = None
  71. def urlopen(url, data=None, proxies=None):
  72.     """urlopen(url [, data]) -> open file-like object"""
  73.     global _urlopener
  74.     if proxies is not None:
  75.         opener = FancyURLopener(proxies=proxies)
  76.     elif not _urlopener:
  77.         opener = FancyURLopener()
  78.         _urlopener = opener
  79.     else:
  80.         opener = _urlopener
  81.     if data is None:
  82.         return opener.open(url)
  83.     else:
  84.         return opener.open(url, data)
  85. def urlretrieve(url, filename=None, reporthook=None, data=None):
  86.     global _urlopener
  87.     if not _urlopener:
  88.         _urlopener = FancyURLopener()
  89.     return _urlopener.retrieve(url, filename, reporthook, data)
  90. def urlcleanup():
  91.     if _urlopener:
  92.         _urlopener.cleanup()
  93.  
  94. # exception raised when downloaded size does not match content-length
  95. class ContentTooShortError(IOError):
  96.     def __init__(self, message, content):
  97.         IOError.__init__(self, message)
  98.         self.content = content
  99.  
  100. ftpcache = {}
  101. class URLopener:
  102.     """Class to open URLs.
  103.     This is a class rather than just a subroutine because we may need
  104.     more than one set of global protocol-specific options.
  105.     Note -- this is a base class for those who don't want the
  106.     automatic handling of errors type 302 (relocated) and 401
  107.     (authorization needed)."""
  108.  
  109.     __tempfiles = None
  110.  
  111.     version = "Python-urllib/%s" % __version__
  112.  
  113.     # Constructor
  114.     def __init__(self, proxies=None, **x509):
  115.         if proxies is None:
  116.             proxies = getproxies()
  117.         assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  118.         self.proxies = proxies
  119.         self.key_file = x509.get('key_file')
  120.         self.cert_file = x509.get('cert_file')
  121.         self.addheaders = [('User-agent', self.version)]
  122.         self.__tempfiles = []
  123.         self.__unlink = os.unlink # See cleanup()
  124.         self.tempcache = None
  125.         # Undocumented feature: if you assign {} to tempcache,
  126.         # it is used to cache files retrieved with
  127.         # self.retrieve().  This is not enabled by default
  128.         # since it does not work for changing documents (and I
  129.         # haven't got the logic to check expiration headers
  130.         # yet).
  131.         self.ftpcache = ftpcache
  132.         # Undocumented feature: you can use a different
  133.         # ftp cache by assigning to the .ftpcache member;
  134.         # in case you want logically independent URL openers
  135.         # XXX This is not threadsafe.  Bah.
  136.  
  137.     def __del__(self):
  138.         self.close()
  139.  
  140.     def close(self):
  141.         self.cleanup()
  142.  
  143.     def cleanup(self):
  144.         # This code sometimes runs when the rest of this module
  145.         # has already been deleted, so it can't use any globals
  146.         # or import anything.
  147.         if self.__tempfiles:
  148.             for file in self.__tempfiles:
  149.                 try:
  150.                     self.__unlink(file)
  151.                 except OSError:
  152.                     pass
  153.             del self.__tempfiles[:]
  154.         if self.tempcache:
  155.             self.tempcache.clear()
  156.  
  157.     def addheader(self, *args):
  158.         """Add a header to be used by the HTTP interface only
  159.         e.g. u.addheader('Accept', 'sound/basic')"""
  160.         self.addheaders.append(args)
  161.  
  162.     # External interface
  163.     def open(self, fullurl, data=None):
  164.         """Use URLopener().open(file) instead of open(file, 'r')."""
  165.         fullurl = unwrap(toBytes(fullurl))
  166.         if self.tempcache and fullurl in self.tempcache:
  167.             filename, headers = self.tempcache[fullurl]
  168.             fp = open(filename, 'rb')
  169.             return addinfourl(fp, headers, fullurl)
  170.         urltype, url = splittype(fullurl)
  171.         if not urltype:
  172.             urltype = 'file'
  173.         if urltype in self.proxies:
  174.             proxy = self.proxies[urltype]
  175.             urltype, proxyhost = splittype(proxy)
  176.             host, selector = splithost(proxyhost)
  177.             url = (host, fullurl) # Signal special case to open_*()
  178.         else:
  179.             proxy = None
  180.         name = 'open_' + urltype
  181.         self.type = urltype
  182.         name = name.replace('-', '_')
  183.         if not hasattr(self, name):
  184.             if proxy:
  185.                 return self.open_unknown_proxy(proxy, fullurl, data)
  186.             else:
  187.                 return self.open_unknown(fullurl, data)
  188.         try:
  189.             if data is None:
  190.                 return getattr(self, name)(url)
  191.             else:
  192.                 return getattr(self, name)(url, data)
  193.         except socket.error, msg:
  194.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  195.  
  196.     def open_unknown(self, fullurl, data=None):
  197.         """Overridable interface to open unknown URL type."""
  198.         type, url = splittype(fullurl)
  199.         raise IOError, ('url error', 'unknown url type', type)
  200.  
  201.     def open_unknown_proxy(self, proxy, fullurl, data=None):
  202.         """Overridable interface to open unknown URL type."""
  203.         type, url = splittype(fullurl)
  204.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  205.  
  206.     # External interface
  207.     def retrieve(self, url, filename=None, reporthook=None, data=None):
  208.         """retrieve(url) returns (filename, headers) for a local object
  209.         or (tempfilename, headers) for a remote object."""
  210.         url = unwrap(toBytes(url))
  211.         if self.tempcache and url in self.tempcache:
  212.             return self.tempcache[url]
  213.         type, url1 = splittype(url)
  214.         if filename is None and (not type or type == 'file'):
  215.             try:
  216.                 fp = self.open_local_file(url1)
  217.                 hdrs = fp.info()
  218.                 del fp
  219.                 return url2pathname(splithost(url1)[1]), hdrs
  220.             except IOError, msg:
  221.                 pass
  222.         fp = self.open(url, data)
  223.         headers = fp.info()
  224.         if filename:
  225.             tfp = open(filename, 'wb')
  226.         else:
  227.             import tempfile
  228.             garbage, path = splittype(url)
  229.             garbage, path = splithost(path or "")
  230.             path, garbage = splitquery(path or "")
  231.             path, garbage = splitattr(path or "")
  232.             suffix = os.path.splitext(path)[1]
  233.             (fd, filename) = tempfile.mkstemp(suffix)
  234.             self.__tempfiles.append(filename)
  235.             tfp = os.fdopen(fd, 'wb')
  236.         result = filename, headers
  237.         if self.tempcache is not None:
  238.             self.tempcache[url] = result
  239.         bs = 1024*8
  240.         size = -1
  241.         read = 0
  242.         blocknum = 0
  243.         if reporthook:
  244.             if "content-length" in headers:
  245.                 size = int(headers["Content-Length"])
  246.             reporthook(blocknum, bs, size)
  247.         while 1:
  248.             block = fp.read(bs)
  249.             if block == "":
  250.                 break
  251.             read += len(block)
  252.             tfp.write(block)
  253.             blocknum += 1
  254.             if reporthook:
  255.                 reporthook(blocknum, bs, size)
  256.         fp.close()
  257.         tfp.close()
  258.         del fp
  259.         del tfp
  260.  
  261.         # raise exception if actual size does not match content-length header
  262.         if size >= 0 and read < size:
  263.             raise ContentTooShortError("retrieval incomplete: got only %i out "
  264.                                        "of %i bytes" % (read, size), result)
  265.  
  266.         return result
  267.  
  268.     # Each method named open_<type> knows how to open that type of URL
  269.  
  270.     def open_http(self, url, data=None):
  271.         """Use HTTP protocol."""
  272.         import httplib
  273.         user_passwd = None
  274.         if isinstance(url, str):
  275.             host, selector = splithost(url)
  276.             if host:
  277.                 user_passwd, host = splituser(host)
  278.                 host = unquote(host)
  279.             realhost = host
  280.         else:
  281.             host, selector = url
  282.             urltype, rest = splittype(selector)
  283.             url = rest
  284.             user_passwd = None
  285.             if urltype.lower() != 'http':
  286.                 realhost = None
  287.             else:
  288.                 realhost, rest = splithost(rest)
  289.                 if realhost:
  290.                     user_passwd, realhost = splituser(realhost)
  291.                 if user_passwd:
  292.                     selector = "%s://%s%s" % (urltype, realhost, rest)
  293.                 if proxy_bypass(realhost):
  294.                     host = realhost
  295.  
  296.             #print "proxy via http:", host, selector
  297.         if not host: raise IOError, ('http error', 'no host given')
  298.         if user_passwd:
  299.             import base64
  300.             auth = base64.encodestring(user_passwd).strip()
  301.         else:
  302.             auth = None
  303.         h = httplib.HTTP(host)
  304.         if data is not None:
  305.             h.putrequest('POST', selector)
  306.             h.putheader('Content-type', 'application/x-www-form-urlencoded')
  307.             h.putheader('Content-length', '%d' % len(data))
  308.         else:
  309.             h.putrequest('GET', selector)
  310.         if auth: h.putheader('Authorization', 'Basic %s' % auth)
  311.         if realhost: h.putheader('Host', realhost)
  312.         for args in self.addheaders: h.putheader(*args)
  313.         h.endheaders()
  314.         if data is not None:
  315.             h.send(data)
  316.         errcode, errmsg, headers = h.getreply()
  317.         fp = h.getfile()
  318.         if errcode == 200:
  319.             return addinfourl(fp, headers, "http:" + url)
  320.         else:
  321.             if data is None:
  322.                 return self.http_error(url, fp, errcode, errmsg, headers)
  323.             else:
  324.                 return self.http_error(url, fp, errcode, errmsg, headers, data)
  325.  
  326.     def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  327.         """Handle http errors.
  328.         Derived class can override this, or provide specific handlers
  329.         named http_error_DDD where DDD is the 3-digit error code."""
  330.         # First check if there's a specific handler for this error
  331.         name = 'http_error_%d' % errcode
  332.         if hasattr(self, name):
  333.             method = getattr(self, name)
  334.             if data is None:
  335.                 result = method(url, fp, errcode, errmsg, headers)
  336.             else:
  337.                 result = method(url, fp, errcode, errmsg, headers, data)
  338.             if result: return result
  339.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  340.  
  341.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  342.         """Default error handler: close the connection and raise IOError."""
  343.         void = fp.read()
  344.         fp.close()
  345.         raise IOError, ('http error', errcode, errmsg, headers)
  346.  
  347.     if hasattr(socket, "ssl"):
  348.         def open_https(self, url, data=None):
  349.             """Use HTTPS protocol."""
  350.             import httplib
  351.             user_passwd = None
  352.             if isinstance(url, str):
  353.                 host, selector = splithost(url)
  354.                 if host:
  355.                     user_passwd, host = splituser(host)
  356.                     host = unquote(host)
  357.                 realhost = host
  358.             else:
  359.                 host, selector = url
  360.                 urltype, rest = splittype(selector)
  361.                 url = rest
  362.                 user_passwd = None
  363.                 if urltype.lower() != 'https':
  364.                     realhost = None
  365.                 else:
  366.                     realhost, rest = splithost(rest)
  367.                     if realhost:
  368.                         user_passwd, realhost = splituser(realhost)
  369.                     if user_passwd:
  370.                         selector = "%s://%s%s" % (urltype, realhost, rest)
  371.                 #print "proxy via https:", host, selector
  372.             if not host: raise IOError, ('https error', 'no host given')
  373.             if user_passwd:
  374.                 import base64
  375.                 auth = base64.encodestring(user_passwd).strip()
  376.             else:
  377.                 auth = None
  378.             h = httplib.HTTPS(host, 0,
  379.                               key_file=self.key_file,
  380.                               cert_file=self.cert_file)
  381.             if data is not None:
  382.                 h.putrequest('POST', selector)
  383.                 h.putheader('Content-type',
  384.                             'application/x-www-form-urlencoded')
  385.                 h.putheader('Content-length', '%d' % len(data))
  386.             else:
  387.                 h.putrequest('GET', selector)
  388.             if auth: h.putheader('Authorization', 'Basic %s' % auth)
  389.             if realhost: h.putheader('Host', realhost)
  390.             for args in self.addheaders: h.putheader(*args)
  391.             h.endheaders()
  392.             if data is not None:
  393.                 h.send(data)
  394.             errcode, errmsg, headers = h.getreply()
  395.             fp = h.getfile()
  396.             if errcode == 200:
  397.                 return addinfourl(fp, headers, "https:" + url)
  398.             else:
  399.                 if data is None:
  400.                     return self.http_error(url, fp, errcode, errmsg, headers)
  401.                 else:
  402.                     return self.http_error(url, fp, errcode, errmsg, headers,
  403.                                            data)
  404.  
  405.     def open_gopher(self, url):
  406.         """Use Gopher protocol."""
  407.         import gopherlib
  408.         host, selector = splithost(url)
  409.         if not host: raise IOError, ('gopher error', 'no host given')
  410.         host = unquote(host)
  411.         type, selector = splitgophertype(selector)
  412.         selector, query = splitquery(selector)
  413.         selector = unquote(selector)
  414.         if query:
  415.             query = unquote(query)
  416.             fp = gopherlib.send_query(selector, query, host)
  417.         else:
  418.             fp = gopherlib.send_selector(selector, host)
  419.         return addinfourl(fp, noheaders(), "gopher:" + url)
  420.  
  421.     def open_file(self, url):
  422.         """Use local file or FTP depending on form of URL."""
  423.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  424.             return self.open_ftp(url)
  425.         else:
  426.             return self.open_local_file(url)
  427.  
  428.     def open_local_file(self, url):
  429.         """Use local file."""
  430.         import mimetypes, mimetools, email.Utils
  431.         try:
  432.             from cStringIO import StringIO
  433.         except ImportError:
  434.             from StringIO import StringIO
  435.         host, file = splithost(url)
  436.         localname = url2pathname(file)
  437.         try:
  438.             stats = os.stat(localname)
  439.         except OSError, e:
  440.             raise IOError(e.errno, e.strerror, e.filename)
  441.         size = stats.st_size
  442.         modified = email.Utils.formatdate(stats.st_mtime, usegmt=True)
  443.         mtype = mimetypes.guess_type(url)[0]
  444.         headers = mimetools.Message(StringIO(
  445.             'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
  446.             (mtype or 'text/plain', size, modified)))
  447.         if not host:
  448.             urlfile = file
  449.             if file[:1] == '/':
  450.                 urlfile = 'file://' + file
  451.             return addinfourl(open(localname, 'rb'),
  452.                               headers, urlfile)
  453.         host, port = splitport(host)
  454.         if not port \
  455.            and socket.gethostbyname(host) in (localhost(), thishost()):
  456.             urlfile = file
  457.             if file[:1] == '/':
  458.                 urlfile = 'file://' + file
  459.             return addinfourl(open(localname, 'rb'),
  460.                               headers, urlfile)
  461.         raise IOError, ('local file error', 'not on local host')
  462.  
  463.     def open_ftp(self, url):
  464.         """Use FTP protocol."""
  465.         import mimetypes, mimetools
  466.         try:
  467.             from cStringIO import StringIO
  468.         except ImportError:
  469.             from StringIO import StringIO
  470.         host, path = splithost(url)
  471.         if not host: raise IOError, ('ftp error', 'no host given')
  472.         host, port = splitport(host)
  473.         user, host = splituser(host)
  474.         if user: user, passwd = splitpasswd(user)
  475.         else: passwd = None
  476.         host = unquote(host)
  477.         user = unquote(user or '')
  478.         passwd = unquote(passwd or '')
  479.         host = socket.gethostbyname(host)
  480.         if not port:
  481.             import ftplib
  482.             port = ftplib.FTP_PORT
  483.         else:
  484.             port = int(port)
  485.         path, attrs = splitattr(path)
  486.         path = unquote(path)
  487.         dirs = path.split('/')
  488.         dirs, file = dirs[:-1], dirs[-1]
  489.         if dirs and not dirs[0]: dirs = dirs[1:]
  490.         if dirs and not dirs[0]: dirs[0] = '/'
  491.         key = user, host, port, '/'.join(dirs)
  492.         # XXX thread unsafe!
  493.         if len(self.ftpcache) > MAXFTPCACHE:
  494.             # Prune the cache, rather arbitrarily
  495.             for k in self.ftpcache.keys():
  496.                 if k != key:
  497.                     v = self.ftpcache[k]
  498.                     del self.ftpcache[k]
  499.                     v.close()
  500.         try:
  501.             if not key in self.ftpcache:
  502.                 self.ftpcache[key] = \
  503.                     ftpwrapper(user, passwd, host, port, dirs)
  504.             if not file: type = 'D'
  505.             else: type = 'I'
  506.             for attr in attrs:
  507.                 attr, value = splitvalue(attr)
  508.                 if attr.lower() == 'type' and \
  509.                    value in ('a', 'A', 'i', 'I', 'd', 'D'):
  510.                     type = value.upper()
  511.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  512.             mtype = mimetypes.guess_type("ftp:" + url)[0]
  513.             headers = ""
  514.             if mtype:
  515.                 headers += "Content-Type: %s\n" % mtype
  516.             if retrlen is not None and retrlen >= 0:
  517.                 headers += "Content-Length: %d\n" % retrlen
  518.             headers = mimetools.Message(StringIO(headers))
  519.             return addinfourl(fp, headers, "ftp:" + url)
  520.         except ftperrors(), msg:
  521.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  522.  
  523.     def open_data(self, url, data=None):
  524.         """Use "data" URL."""
  525.         # ignore POSTed data
  526.         #
  527.         # syntax of data URLs:
  528.         # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
  529.         # mediatype := [ type "/" subtype ] *( ";" parameter )
  530.         # data      := *urlchar
  531.         # parameter := attribute "=" value
  532.         import mimetools
  533.         try:
  534.             from cStringIO import StringIO
  535.         except ImportError:
  536.             from StringIO import StringIO
  537.         try:
  538.             [type, data] = url.split(',', 1)
  539.         except ValueError:
  540.             raise IOError, ('data error', 'bad data URL')
  541.         if not type:
  542.             type = 'text/plain;charset=US-ASCII'
  543.         semi = type.rfind(';')
  544.         if semi >= 0 and '=' not in type[semi:]:
  545.             encoding = type[semi+1:]
  546.             type = type[:semi]
  547.         else:
  548.             encoding = ''
  549.         msg = []
  550.         msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
  551.                                             time.gmtime(time.time())))
  552.         msg.append('Content-type: %s' % type)
  553.         if encoding == 'base64':
  554.             import base64
  555.             data = base64.decodestring(data)
  556.         else:
  557.             data = unquote(data)
  558.         msg.append('Content-length: %d' % len(data))
  559.         msg.append('')
  560.         msg.append(data)
  561.         msg = '\n'.join(msg)
  562.         f = StringIO(msg)
  563.         headers = mimetools.Message(f, 0)
  564.         #f.fileno = None     # needed for addinfourl
  565.         return addinfourl(f, headers, url)
  566.  
  567.  
  568. class FancyURLopener(URLopener):
  569.     """Derived class with handlers for errors we can handle (perhaps)."""
  570.  
  571.     def __init__(self, *args, **kwargs):
  572.         URLopener.__init__(self, *args, **kwargs)
  573.         self.auth_cache = {}
  574.         self.tries = 0
  575.         self.maxtries = 10
  576.  
  577.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  578.         """Default error handling -- don't raise an exception."""
  579.         return addinfourl(fp, headers, "http:" + url)
  580.  
  581.     def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  582.         """Error 302 -- relocated (temporarily)."""
  583.         self.tries += 1
  584.         if self.maxtries and self.tries >= self.maxtries:
  585.             if hasattr(self, "http_error_500"):
  586.                 meth = self.http_error_500
  587.             else:
  588.                 meth = self.http_error_default
  589.             self.tries = 0
  590.             return meth(url, fp, 500,
  591.                         "Internal Server Error: Redirect Recursion", headers)
  592.         result = self.redirect_internal(url, fp, errcode, errmsg, headers,
  593.                                         data)
  594.         self.tries = 0
  595.         return result
  596.  
  597.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  598.         if 'location' in headers:
  599.             newurl = headers['location']
  600.         elif 'uri' in headers:
  601.             newurl = headers['uri']
  602.         else:
  603.             return
  604.         void = fp.read()
  605.         fp.close()
  606.         # In case the server sent a relative URL, join with original:
  607.         newurl = basejoin(self.type + ":" + url, newurl)
  608.         return self.open(newurl)
  609.  
  610.     def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  611.         """Error 301 -- also relocated (permanently)."""
  612.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  613.  
  614.     def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
  615.         """Error 303 -- also relocated (essentially identical to 302)."""
  616.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  617.  
  618.     def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
  619.         """Error 307 -- relocated, but turn POST into error."""
  620.         if data is None:
  621.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  622.         else:
  623.             return self.http_error_default(url, fp, errcode, errmsg, headers)
  624.  
  625.     def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
  626.         """Error 401 -- authentication required.
  627.         See this URL for a description of the basic authentication scheme:
  628.         http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt"""
  629.         if not 'www-authenticate' in headers:
  630.             URLopener.http_error_default(self, url, fp,
  631.                                          errcode, errmsg, headers)
  632.         stuff = headers['www-authenticate']
  633.         import re
  634.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  635.         if not match:
  636.             URLopener.http_error_default(self, url, fp,
  637.                                          errcode, errmsg, headers)
  638.         scheme, realm = match.groups()
  639.         if scheme.lower() != 'basic':
  640.             URLopener.http_error_default(self, url, fp,
  641.                                          errcode, errmsg, headers)
  642.         name = 'retry_' + self.type + '_basic_auth'
  643.         if data is None:
  644.             return getattr(self,name)(url, realm)
  645.         else:
  646.             return getattr(self,name)(url, realm, data)
  647.  
  648.     def retry_http_basic_auth(self, url, realm, data=None):
  649.         host, selector = splithost(url)
  650.         i = host.find('@') + 1
  651.         host = host[i:]
  652.         user, passwd = self.get_user_passwd(host, realm, i)
  653.         if not (user or passwd): return None
  654.         host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  655.         newurl = 'http://' + host + selector
  656.         if data is None:
  657.             return self.open(newurl)
  658.         else:
  659.             return self.open(newurl, data)
  660.  
  661.     def retry_https_basic_auth(self, url, realm, data=None):
  662.         host, selector = splithost(url)
  663.         i = host.find('@') + 1
  664.         host = host[i:]
  665.         user, passwd = self.get_user_passwd(host, realm, i)
  666.         if not (user or passwd): return None
  667.         host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  668.         newurl = '//' + host + selector
  669.         return self.open_https(newurl, data)
  670.  
  671.     def get_user_passwd(self, host, realm, clear_cache = 0):
  672.         key = realm + '@' + host.lower()
  673.         if key in self.auth_cache:
  674.             if clear_cache:
  675.                 del self.auth_cache[key]
  676.             else:
  677.                 return self.auth_cache[key]
  678.         user, passwd = self.prompt_user_passwd(host, realm)
  679.         if user or passwd: self.auth_cache[key] = (user, passwd)
  680.         return user, passwd
  681.  
  682.     def prompt_user_passwd(self, host, realm):
  683.         """Override this in a GUI environment!"""
  684.         import getpass
  685.         try:
  686.             user = raw_input("Enter username for %s at %s: " % (realm,
  687.                                                                 host))
  688.             passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  689.                 (user, realm, host))
  690.             return user, passwd
  691.         except KeyboardInterrupt:
  692.             print
  693.             return None, None
  694.  
  695.  
  696. # Utility functions
  697.  
  698. _localhost = None
  699. def localhost():
  700.     """Return the IP address of the magic hostname 'localhost'."""
  701.     global _localhost
  702.     if _localhost is None:
  703.         _localhost = socket.gethostbyname('localhost')
  704.     return _localhost
  705.  
  706. _thishost = None
  707. def thishost():
  708.     """Return the IP address of the current host."""
  709.     global _thishost
  710.     if _thishost is None:
  711.         _thishost = socket.gethostbyname(socket.gethostname())
  712.     return _thishost
  713.  
  714. _ftperrors = None
  715. def ftperrors():
  716.     """Return the set of errors raised by the FTP class."""
  717.     global _ftperrors
  718.     if _ftperrors is None:
  719.         import ftplib
  720.         _ftperrors = ftplib.all_errors
  721.     return _ftperrors
  722.  
  723. _noheaders = None
  724. def noheaders():
  725.     """Return an empty mimetools.Message object."""
  726.     global _noheaders
  727.     if _noheaders is None:
  728.         import mimetools
  729.         try:
  730.             from cStringIO import StringIO
  731.         except ImportError:
  732.             from StringIO import StringIO
  733.         _noheaders = mimetools.Message(StringIO(), 0)
  734.         _noheaders.fp.close()   # Recycle file descriptor
  735.     return _noheaders
  736.  
  737.  
  738. # Utility classes
  739.  
  740. class ftpwrapper:
  741.     """Class used by open_ftp() for cache of open FTP connections."""
  742.  
  743.     def __init__(self, user, passwd, host, port, dirs):
  744.         self.user = user
  745.         self.passwd = passwd
  746.         self.host = host
  747.         self.port = port
  748.         self.dirs = dirs
  749.         self.init()
  750.  
  751.     def init(self):
  752.         import ftplib
  753.         self.busy = 0
  754.         self.ftp = ftplib.FTP()
  755.         self.ftp.connect(self.host, self.port)
  756.         self.ftp.login(self.user, self.passwd)
  757.         for dir in self.dirs:
  758.             self.ftp.cwd(dir)
  759.  
  760.     def retrfile(self, file, type):
  761.         import ftplib
  762.         self.endtransfer()
  763.         if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  764.         else: cmd = 'TYPE ' + type; isdir = 0
  765.         try:
  766.             self.ftp.voidcmd(cmd)
  767.         except ftplib.all_errors:
  768.             self.init()
  769.             self.ftp.voidcmd(cmd)
  770.         conn = None
  771.         if file and not isdir:
  772.             # Try to retrieve as a file
  773.             try:
  774.                 cmd = 'RETR ' + file
  775.                 conn = self.ftp.ntransfercmd(cmd)
  776.             except ftplib.error_perm, reason:
  777.                 if str(reason)[:3] != '550':
  778.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  779.         if not conn:
  780.             # Set transfer mode to ASCII!
  781.             self.ftp.voidcmd('TYPE A')
  782.             # Try a directory listing
  783.             if file: cmd = 'LIST ' + file
  784.             else: cmd = 'LIST'
  785.             conn = self.ftp.ntransfercmd(cmd)
  786.         self.busy = 1
  787.         # Pass back both a suitably decorated object and a retrieval length
  788.         return (addclosehook(conn[0].makefile('rb'),
  789.                              self.endtransfer), conn[1])
  790.     def endtransfer(self):
  791.         if not self.busy:
  792.             return
  793.         self.busy = 0
  794.         try:
  795.             self.ftp.voidresp()
  796.         except ftperrors():
  797.             pass
  798.  
  799.     def close(self):
  800.         self.endtransfer()
  801.         try:
  802.             self.ftp.close()
  803.         except ftperrors():
  804.             pass
  805.  
  806. class addbase:
  807.     """Base class for addinfo and addclosehook."""
  808.  
  809.     def __init__(self, fp):
  810.         self.fp = fp
  811.         self.read = self.fp.read
  812.         self.readline = self.fp.readline
  813.         if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
  814.         if hasattr(self.fp, "fileno"):
  815.             self.fileno = self.fp.fileno
  816.         else:
  817.             self.fileno = lambda: None
  818.         if hasattr(self.fp, "__iter__"):
  819.             self.__iter__ = self.fp.__iter__
  820.             if hasattr(self.fp, "next"):
  821.                 self.next = self.fp.next
  822.  
  823.     def __repr__(self):
  824.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
  825.                                              id(self), self.fp)
  826.  
  827.     def close(self):
  828.         self.read = None
  829.         self.readline = None
  830.         self.readlines = None
  831.         self.fileno = None
  832.         if self.fp: self.fp.close()
  833.         self.fp = None
  834.  
  835. class addclosehook(addbase):
  836.     """Class to add a close hook to an open file."""
  837.  
  838.     def __init__(self, fp, closehook, *hookargs):
  839.         addbase.__init__(self, fp)
  840.         self.closehook = closehook
  841.         self.hookargs = hookargs
  842.  
  843.     def close(self):
  844.         addbase.close(self)
  845.         if self.closehook:
  846.             self.closehook(*self.hookargs)
  847.             self.closehook = None
  848.             self.hookargs = None
  849.  
  850. class addinfo(addbase):
  851.     """class to add an info() method to an open file."""
  852.  
  853.     def __init__(self, fp, headers):
  854.         addbase.__init__(self, fp)
  855.         self.headers = headers
  856.  
  857.     def info(self):
  858.         return self.headers
  859.  
  860. class addinfourl(addbase):
  861.     """class to add info() and geturl() methods to an open file."""
  862.  
  863.     def __init__(self, fp, headers, url):
  864.         addbase.__init__(self, fp)
  865.         self.headers = headers
  866.         self.url = url
  867.  
  868.     def info(self):
  869.         return self.headers
  870.  
  871.     def geturl(self):
  872.         return self.url
  873.  
  874.  
  875. # Utilities to parse URLs (most of these return None for missing parts):
  876. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  877. # splittype('type:opaquestring') --> 'type', 'opaquestring'
  878. # splithost('//host[:port]/path') --> 'host[:port]', '/path'
  879. # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
  880. # splitpasswd('user:passwd') -> 'user', 'passwd'
  881. # splitport('host:port') --> 'host', 'port'
  882. # splitquery('/path?query') --> '/path', 'query'
  883. # splittag('/path#tag') --> '/path', 'tag'
  884. # splitattr('/path;attr1=value1;attr2=value2;...') ->
  885. #   '/path', ['attr1=value1', 'attr2=value2', ...]
  886. # splitvalue('attr=value') --> 'attr', 'value'
  887. # splitgophertype('/Xselector') --> 'X', 'selector'
  888. # unquote('abc%20def') -> 'abc def'
  889. # quote('abc def') -> 'abc%20def')
  890.  
  891. try:
  892.     unicode
  893. except NameError:
  894.     def _is_unicode(x):
  895.         return 0
  896. else:
  897.     def _is_unicode(x):
  898.         return isinstance(x, unicode)
  899.  
  900. def toBytes(url):
  901.     """toBytes(u"URL") --> 'URL'."""
  902.     # Most URL schemes require ASCII. If that changes, the conversion
  903.     # can be relaxed
  904.     if _is_unicode(url):
  905.         try:
  906.             url = url.encode("ASCII")
  907.         except UnicodeError:
  908.             raise UnicodeError("URL " + repr(url) +
  909.                                " contains non-ASCII characters")
  910.     return url
  911.  
  912. def unwrap(url):
  913.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  914.     url = url.strip()
  915.     if url[:1] == '<' and url[-1:] == '>':
  916.         url = url[1:-1].strip()
  917.     if url[:4] == 'URL:': url = url[4:].strip()
  918.     return url
  919.  
  920. _typeprog = None
  921. def splittype(url):
  922.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  923.     global _typeprog
  924.     if _typeprog is None:
  925.         import re
  926.         _typeprog = re.compile('^([^/:]+):')
  927.  
  928.     match = _typeprog.match(url)
  929.     if match:
  930.         scheme = match.group(1)
  931.         return scheme.lower(), url[len(scheme) + 1:]
  932.     return None, url
  933.  
  934. _hostprog = None
  935. def splithost(url):
  936.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  937.     global _hostprog
  938.     if _hostprog is None:
  939.         import re
  940.         _hostprog = re.compile('^//([^/]*)(.*)$')
  941.  
  942.     match = _hostprog.match(url)
  943.     if match: return match.group(1, 2)
  944.     return None, url
  945.  
  946. _userprog = None
  947. def splituser(host):
  948.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  949.     global _userprog
  950.     if _userprog is None:
  951.         import re
  952.         _userprog = re.compile('^(.*)@(.*)$')
  953.  
  954.     match = _userprog.match(host)
  955.     if match: return map(unquote, match.group(1, 2))
  956.     return None, host
  957.  
  958. _passwdprog = None
  959. def splitpasswd(user):
  960.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  961.     global _passwdprog
  962.     if _passwdprog is None:
  963.         import re
  964.         _passwdprog = re.compile('^([^:]*):(.*)$')
  965.  
  966.     match = _passwdprog.match(user)
  967.     if match: return match.group(1, 2)
  968.     return user, None
  969.  
  970. # splittag('/path#tag') --> '/path', 'tag'
  971. _portprog = None
  972. def splitport(host):
  973.     """splitport('host:port') --> 'host', 'port'."""
  974.     global _portprog
  975.     if _portprog is None:
  976.         import re
  977.         _portprog = re.compile('^(.*):([0-9]+)$')
  978.  
  979.     match = _portprog.match(host)
  980.     if match: return match.group(1, 2)
  981.     return host, None
  982.  
  983. _nportprog = None
  984. def splitnport(host, defport=-1):
  985.     """Split host and port, returning numeric port.
  986.     Return given default port if no ':' found; defaults to -1.
  987.     Return numerical port if a valid number are found after ':'.
  988.     Return None if ':' but not a valid number."""
  989.     global _nportprog
  990.     if _nportprog is None:
  991.         import re
  992.         _nportprog = re.compile('^(.*):(.*)$')
  993.  
  994.     match = _nportprog.match(host)
  995.     if match:
  996.         host, port = match.group(1, 2)
  997.         try:
  998.             if not port: raise ValueError, "no digits"
  999.             nport = int(port)
  1000.         except ValueError:
  1001.             nport = None
  1002.         return host, nport
  1003.     return host, defport
  1004.  
  1005. _queryprog = None
  1006. def splitquery(url):
  1007.     """splitquery('/path?query') --> '/path', 'query'."""
  1008.     global _queryprog
  1009.     if _queryprog is None:
  1010.         import re
  1011.         _queryprog = re.compile('^(.*)\?([^?]*)$')
  1012.  
  1013.     match = _queryprog.match(url)
  1014.     if match: return match.group(1, 2)
  1015.     return url, None
  1016.  
  1017. _tagprog = None
  1018. def splittag(url):
  1019.     """splittag('/path#tag') --> '/path', 'tag'."""
  1020.     global _tagprog
  1021.     if _tagprog is None:
  1022.         import re
  1023.         _tagprog = re.compile('^(.*)#([^#]*)$')
  1024.  
  1025.     match = _tagprog.match(url)
  1026.     if match: return match.group(1, 2)
  1027.     return url, None
  1028.  
  1029. def splitattr(url):
  1030.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1031.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1032.     words = url.split(';')
  1033.     return words[0], words[1:]
  1034.  
  1035. _valueprog = None
  1036. def splitvalue(attr):
  1037.     """splitvalue('attr=value') --> 'attr', 'value'."""
  1038.     global _valueprog
  1039.     if _valueprog is None:
  1040.         import re
  1041.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1042.  
  1043.     match = _valueprog.match(attr)
  1044.     if match: return match.group(1, 2)
  1045.     return attr, None
  1046.  
  1047. def splitgophertype(selector):
  1048.     """splitgophertype('/Xselector') --> 'X', 'selector'."""
  1049.     if selector[:1] == '/' and selector[1:2]:
  1050.         return selector[1], selector[2:]
  1051.     return None, selector
  1052.  
  1053. _hextochr = dict(('%02x' % i, chr(i)) for i in range(256))
  1054. _hextochr.update(('%02X' % i, chr(i)) for i in range(256))
  1055.  
  1056. def unquote(s):
  1057.     """unquote('abc%20def') -> 'abc def'."""
  1058.     res = s.split('%')
  1059.     for i in xrange(1, len(res)):
  1060.         item = res[i]
  1061.         try:
  1062.             res[i] = _hextochr[item[:2]] + item[2:]
  1063.         except KeyError:
  1064.             res[i] = '%' + item
  1065.         except UnicodeDecodeError:
  1066.             res[i] = unichr(int(item[:2], 16)) + item[2:]
  1067.     return "".join(res)
  1068.  
  1069. def unquote_plus(s):
  1070.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1071.     s = s.replace('+', ' ')
  1072.     return unquote(s)
  1073.  
  1074. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1075.                'abcdefghijklmnopqrstuvwxyz'
  1076.                '0123456789' '_.-')
  1077. _safemaps = {}
  1078.  
  1079. def quote(s, safe = '/'):
  1080.     """quote('abc def') -> 'abc%20def'
  1081.  
  1082.     Each part of a URL, e.g. the path info, the query, etc., has a
  1083.     different set of reserved characters that must be quoted.
  1084.  
  1085.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1086.     the following reserved characters.
  1087.  
  1088.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1089.                   "$" | ","
  1090.  
  1091.     Each of these characters is reserved in some component of a URL,
  1092.     but not necessarily in all of them.
  1093.  
  1094.     By default, the quote function is intended for quoting the path
  1095.     section of a URL.  Thus, it will not encode '/'.  This character
  1096.     is reserved, but in typical usage the quote function is being
  1097.     called on a path where the existing slash characters are used as
  1098.     reserved characters.
  1099.     """
  1100.     cachekey = (safe, always_safe)
  1101.     try:
  1102.         safe_map = _safemaps[cachekey]
  1103.     except KeyError:
  1104.         safe += always_safe
  1105.         safe_map = {}
  1106.         for i in range(256):
  1107.             c = chr(i)
  1108.             safe_map[c] = (c in safe) and c or ('%%%02X' % i)
  1109.         _safemaps[cachekey] = safe_map
  1110.     res = map(safe_map.__getitem__, s)
  1111.     return ''.join(res)
  1112.  
  1113. def quote_plus(s, safe = ''):
  1114.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1115.     if ' ' in s:
  1116.         s = quote(s, safe + ' ')
  1117.         return s.replace(' ', '+')
  1118.     return quote(s, safe)
  1119.  
  1120. def urlencode(query,doseq=0):
  1121.     """Encode a sequence of two-element tuples or dictionary into a URL query string.
  1122.  
  1123.     If any values in the query arg are sequences and doseq is true, each
  1124.     sequence element is converted to a separate parameter.
  1125.  
  1126.     If the query arg is a sequence of two-element tuples, the order of the
  1127.     parameters in the output will match the order of parameters in the
  1128.     input.
  1129.     """
  1130.  
  1131.     if hasattr(query,"items"):
  1132.         # mapping objects
  1133.         query = query.items()
  1134.     else:
  1135.         # it's a bother at times that strings and string-like objects are
  1136.         # sequences...
  1137.         try:
  1138.             # non-sequence items should not work with len()
  1139.             # non-empty strings will fail this
  1140.             if len(query) and not isinstance(query[0], tuple):
  1141.                 raise TypeError
  1142.             # zero-length sequences of all types will get here and succeed,
  1143.             # but that's a minor nit - since the original implementation
  1144.             # allowed empty dicts that type of behavior probably should be
  1145.             # preserved for consistency
  1146.         except TypeError:
  1147.             ty,va,tb = sys.exc_info()
  1148.             raise TypeError, "not a valid non-string sequence or mapping object", tb
  1149.  
  1150.     l = []
  1151.     if not doseq:
  1152.         # preserve old behavior
  1153.         for k, v in query:
  1154.             k = quote_plus(str(k))
  1155.             v = quote_plus(str(v))
  1156.             l.append(k + '=' + v)
  1157.     else:
  1158.         for k, v in query:
  1159.             k = quote_plus(str(k))
  1160.             if isinstance(v, str):
  1161.                 v = quote_plus(v)
  1162.                 l.append(k + '=' + v)
  1163.             elif _is_unicode(v):
  1164.                 # is there a reasonable way to convert to ASCII?
  1165.                 # encode generates a string, but "replace" or "ignore"
  1166.                 # lose information and "strict" can raise UnicodeError
  1167.                 v = quote_plus(v.encode("ASCII","replace"))
  1168.                 l.append(k + '=' + v)
  1169.             else:
  1170.                 try:
  1171.                     # is this a sufficient test for sequence-ness?
  1172.                     x = len(v)
  1173.                 except TypeError:
  1174.                     # not a sequence
  1175.                     v = quote_plus(str(v))
  1176.                     l.append(k + '=' + v)
  1177.                 else:
  1178.                     # loop over the sequence
  1179.                     for elt in v:
  1180.                         l.append(k + '=' + quote_plus(str(elt)))
  1181.     return '&'.join(l)
  1182.  
  1183. # Proxy handling
  1184. def getproxies_environment():
  1185.     """Return a dictionary of scheme -> proxy server URL mappings.
  1186.  
  1187.     Scan the environment for variables named <scheme>_proxy;
  1188.     this seems to be the standard convention.  If you need a
  1189.     different way, you can pass a proxies dictionary to the
  1190.     [Fancy]URLopener constructor.
  1191.  
  1192.     """
  1193.     proxies = {}
  1194.     for name, value in os.environ.items():
  1195.         name = name.lower()
  1196.         if value and name[-6:] == '_proxy':
  1197.             proxies[name[:-6]] = value
  1198.     return proxies
  1199.  
  1200. if sys.platform == 'darwin':
  1201.     def getproxies_internetconfig():
  1202.         """Return a dictionary of scheme -> proxy server URL mappings.
  1203.  
  1204.         By convention the mac uses Internet Config to store
  1205.         proxies.  An HTTP proxy, for instance, is stored under
  1206.         the HttpProxy key.
  1207.  
  1208.         """
  1209.         try:
  1210.             import ic
  1211.         except ImportError:
  1212.             return {}
  1213.  
  1214.         try:
  1215.             config = ic.IC()
  1216.         except ic.error:
  1217.             return {}
  1218.         proxies = {}
  1219.         # HTTP:
  1220.         if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
  1221.             try:
  1222.                 value = config['HTTPProxyHost']
  1223.             except ic.error:
  1224.                 pass
  1225.             else:
  1226.                 proxies['http'] = 'http://%s' % value
  1227.         # FTP: XXXX To be done.
  1228.         # Gopher: XXXX To be done.
  1229.         return proxies
  1230.  
  1231.     def proxy_bypass(x):
  1232.         return 0
  1233.  
  1234.     def getproxies():
  1235.         return getproxies_environment() or getproxies_internetconfig()
  1236.  
  1237. elif os.name == 'nt':
  1238.     def getproxies_registry():
  1239.         """Return a dictionary of scheme -> proxy server URL mappings.
  1240.  
  1241.         Win32 uses the registry to store proxies.
  1242.  
  1243.         """
  1244.         proxies = {}
  1245.         try:
  1246.             import _winreg
  1247.         except ImportError:
  1248.             # Std module, so should be around - but you never know!
  1249.             return proxies
  1250.         try:
  1251.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
  1252.                 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  1253.             proxyEnable = _winreg.QueryValueEx(internetSettings,
  1254.                                                'ProxyEnable')[0]
  1255.             if proxyEnable:
  1256.                 # Returned as Unicode but problems if not converted to ASCII
  1257.                 proxyServer = str(_winreg.QueryValueEx(internetSettings,
  1258.                                                        'ProxyServer')[0])
  1259.                 if '=' in proxyServer:
  1260.                     # Per-protocol settings
  1261.                     for p in proxyServer.split(';'):
  1262.                         protocol, address = p.split('=', 1)
  1263.                         # See if address has a type:// prefix
  1264.                         import re
  1265.                         if not re.match('^([^/:]+)://', address):
  1266.                             address = '%s://%s' % (protocol, address)
  1267.                         proxies[protocol] = address
  1268.                 else:
  1269.                     # Use one setting for all protocols
  1270.                     if proxyServer[:5] == 'http:':
  1271.                         proxies['http'] = proxyServer
  1272.                     else:
  1273.                         proxies['http'] = 'http://%s' % proxyServer
  1274.                         proxies['ftp'] = 'ftp://%s' % proxyServer
  1275.             internetSettings.Close()
  1276.         except (WindowsError, ValueError, TypeError):
  1277.             # Either registry key not found etc, or the value in an
  1278.             # unexpected format.
  1279.             # proxies already set up to be empty so nothing to do
  1280.             pass
  1281.         return proxies
  1282.  
  1283.     def getproxies():
  1284.         """Return a dictionary of scheme -> proxy server URL mappings.
  1285.  
  1286.         Returns settings gathered from the environment, if specified,
  1287.         or the registry.
  1288.  
  1289.         """
  1290.         return getproxies_environment() or getproxies_registry()
  1291.  
  1292.     def proxy_bypass(host):
  1293.         try:
  1294.             import _winreg
  1295.             import re
  1296.         except ImportError:
  1297.             # Std modules, so should be around - but you never know!
  1298.             return 0
  1299.         try:
  1300.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
  1301.                 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  1302.             proxyEnable = _winreg.QueryValueEx(internetSettings,
  1303.                                                'ProxyEnable')[0]
  1304.             proxyOverride = str(_winreg.QueryValueEx(internetSettings,
  1305.                                                      'ProxyOverride')[0])
  1306.             # ^^^^ Returned as Unicode but problems if not converted to ASCII
  1307.         except WindowsError:
  1308.             return 0
  1309.         if not proxyEnable or not proxyOverride:
  1310.             return 0
  1311.         # try to make a host list from name and IP address.
  1312.         host = [host]
  1313.         try:
  1314.             addr = socket.gethostbyname(host[0])
  1315.             if addr != host:
  1316.                 host.append(addr)
  1317.         except socket.error:
  1318.             pass
  1319.         # make a check value list from the registry entry: replace the
  1320.         # '<local>' string by the localhost entry and the corresponding
  1321.         # canonical entry.
  1322.         proxyOverride = proxyOverride.split(';')
  1323.         i = 0
  1324.         while i < len(proxyOverride):
  1325.             if proxyOverride[i] == '<local>':
  1326.                 proxyOverride[i:i+1] = ['localhost',
  1327.                                         '127.0.0.1',
  1328.                                         socket.gethostname(),
  1329.                                         socket.gethostbyname(
  1330.                                             socket.gethostname())]
  1331.             i += 1
  1332.         # print proxyOverride
  1333.         # now check if we match one of the registry values.
  1334.         for test in proxyOverride:
  1335.             test = test.replace(".", r"\.")     # mask dots
  1336.             test = test.replace("*", r".*")     # change glob sequence
  1337.             test = test.replace("?", r".")      # change glob char
  1338.             for val in host:
  1339.                 # print "%s <--> %s" %( test, val )
  1340.                 if re.match(test, val, re.I):
  1341.                     return 1
  1342.         return 0
  1343.  
  1344. else:
  1345.     # By default use environment variables
  1346.     getproxies = getproxies_environment
  1347.  
  1348.     def proxy_bypass(host):
  1349.         return 0
  1350.  
  1351. # Test and time quote() and unquote()
  1352. def test1():
  1353.     s = ''
  1354.     for i in range(256): s = s + chr(i)
  1355.     s = s*4
  1356.     t0 = time.time()
  1357.     qs = quote(s)
  1358.     uqs = unquote(qs)
  1359.     t1 = time.time()
  1360.     if uqs != s:
  1361.         print 'Wrong!'
  1362.     print repr(s)
  1363.     print repr(qs)
  1364.     print repr(uqs)
  1365.     print round(t1 - t0, 3), 'sec'
  1366.  
  1367.  
  1368. def reporthook(blocknum, blocksize, totalsize):
  1369.     # Report during remote transfers
  1370.     print "Block number: %d, Block size: %d, Total size: %d" % (
  1371.         blocknum, blocksize, totalsize)
  1372.  
  1373. # Test program
  1374. def test(args=[]):
  1375.     if not args:
  1376.         args = [
  1377.             '/etc/passwd',
  1378.             'file:/etc/passwd',
  1379.             'file://localhost/etc/passwd',
  1380.             'ftp://ftp.python.org/pub/python/README',
  1381. ##          'gopher://gopher.micro.umn.edu/1/',
  1382.             'http://www.python.org/index.html',
  1383.             ]
  1384.         if hasattr(URLopener, "open_https"):
  1385.             args.append('https://synergy.as.cmu.edu/~geek/')
  1386.     try:
  1387.         for url in args:
  1388.             print '-'*10, url, '-'*10
  1389.             fn, h = urlretrieve(url, None, reporthook)
  1390.             print fn
  1391.             if h:
  1392.                 print '======'
  1393.                 for k in h.keys(): print k + ':', h[k]
  1394.                 print '======'
  1395.             fp = open(fn, 'rb')
  1396.             data = fp.read()
  1397.             del fp
  1398.             if '\r' in data:
  1399.                 table = string.maketrans("", "")
  1400.                 data = data.translate(table, "\r")
  1401.             print data
  1402.             fn, h = None, None
  1403.         print '-'*40
  1404.     finally:
  1405.         urlcleanup()
  1406.  
  1407. def main():
  1408.     import getopt, sys
  1409.     try:
  1410.         opts, args = getopt.getopt(sys.argv[1:], "th")
  1411.     except getopt.error, msg:
  1412.         print msg
  1413.         print "Use -h for help"
  1414.         return
  1415.     t = 0
  1416.     for o, a in opts:
  1417.         if o == '-t':
  1418.             t = t + 1
  1419.         if o == '-h':
  1420.             print "Usage: python urllib.py [-t] [url ...]"
  1421.             print "-t runs self-test;",
  1422.             print "otherwise, contents of urls are printed"
  1423.             return
  1424.     if t:
  1425.         if t > 1:
  1426.             test1()
  1427.         test(args)
  1428.     else:
  1429.         if not args:
  1430.             print "Use -h for help"
  1431.         for url in args:
  1432.             print urlopen(url).read(),
  1433.  
  1434. # Run test program when run as a script
  1435. if __name__ == '__main__':
  1436.     main()
  1437.